from selenium import webdriver
import time, re, PIL.Image as image, os, cv2
from urllib import request
from selenium.webdriver import ActionChains

def get_image(elm):

    location_list = []
    for background_image in elm:
        location = {}
        # 在html里面解析出小图片的url地址，还有长高的数值
        location["x"] = int(re.findall("background-image: url\(\"?(.*)\"?\); background-position: (.*)px (.*)px;",background_image.get_attribute("style"))[0][1])
        location["y"] = int(re.findall("background-image: url\(\"?(.*)\"?\); background-position: (.*)px (.*)px;",background_image.get_attribute("style"))[0][2])
        imageurl = re.findall("background-image: url\(\"?([^\"]*)\"?\); background-position",background_image.get_attribute("style"))[0]
        location_list.append(location)
    response = request.urlopen(imageurl)
    imageName = imageurl.split("/")[-1]
    with open(imageName, "wb") as f:
        f.write(response.read())
        f.close()

    image = get_merge_image(imageName, location_list)
    image.save('2.png')
    os.remove(imageName)
    return image

def get_merge_image(filename,location_list):
    #打开图片文件
    im = image.open(filename)
    im_list_upper=[]
    # 拷贝图片
    for location in location_list:
            im_list_upper.append(im.crop((abs(location["x"]), abs(location["y"]), abs(location["x"])+20, abs(location["y"])+80)))
    new_im = image.new("RGB", (300, 160))
    x_offset = 0
    y_offset = 0
    i = 0
    for im in im_list_upper:
        if i == 15:
            x_offset = 0
            y_offset = 80

        new_im.paste(im, (x_offset, y_offset))
        x_offset += im.size[0]
        i += 1
    return new_im

def getLocation(img):
    x = []
    y = []
    images = image.open("2.png")
    for i in range(300):
        for j in range(160):
            # print(i, j, images.getpixel((i, j)))
            if images.getpixel((i, j)) == (255, 255, 255):
                # print(i,j)
                if images.getpixel((i + 7, j)) == (255, 255, 255):
                    x.append(i)
                    y.append(j)
    print(x, y)
    return {'x': (max(x) + min(x)) // 2, 'y': (max(y) + min(y)) // 2}


def main(keyword):
    # phantomjs = '../bin/phantomjs.exe'
    #
    # desired_capabilities = webdriver.DesiredCapabilities.PHANTOMJS.copy()
    # desired_capabilities['phantomjs.page.settings.loadImages'] = False
    # driver = webdriver.PhantomJS(executable_path=phantomjs, desired_capabilities=desired_capabilities)
    driver = webdriver.Firefox()
    driver.get('https://my.luosimao.com/auth/register')

    driver.switch_to_frame(driver.find_element_by_id('captcha_widget'))
    driver.find_element_by_class_name('captcha-widget-menu').click()
    driver.switch_to_default_content()
    driver.switch_to_frame(driver.find_element_by_id('captcha_frame'))
    time.sleep(1)
    get_image(driver.find_elements_by_xpath('//div[@class="captcha-list"]/div'))
    location = getLocation('2.png')
    action = ActionChains(driver)
    elm = driver.find_element_by_class_name('lc-refresh')
    refloc = elm.location
    x_offest = refloc['x']-location['x']
    y_offest = refloc['y']-location['y']
    print(x_offest,y_offest)
    action.move_to_element_with_offset(elm, -x_offest, -y_offest).perform()
    action.click().perform()
    driver.switch_to_default_content()
    result = re.compile(r'name="luotest_response" value="(.*?)"').findall(driver.page_source)
    print(driver.page_source)

main('可口可乐')



